package com.hmdp.service.impl;

import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_TTL;


/**
 * <p>
 *  服务实现类
 * </p>
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result queryTypeList() {
        String key = CACHE_SHOP_TYPE_KEY;
        //1.查询所有商铺
        String shopTypeListJson = stringRedisTemplate.opsForValue().get(key);
        // 2. 判断缓存是否存在
        if (StrUtil.isNotBlank(shopTypeListJson)) {
            // 3. 存在，反序列化并返回
            List<ShopType> typeList = JSONUtil.toList(shopTypeListJson, ShopType.class);
            return Result.ok(typeList);
        }

        // 4. 不存在，查询数据库
        List<ShopType> typeList = query().orderByAsc("sort").list();

        // 5. 判断数据库查询结果
        if (typeList == null || typeList.isEmpty()) {
            return Result.fail("商铺类型不存在");
        }

        // 6. 存在，序列化后写入Redis缓存
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(typeList), CACHE_SHOP_TYPE_TTL, TimeUnit.MINUTES);

        // 7. 返回结果
        return Result.ok(typeList);

    }
}
